import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Vector;


public class SchoolServer {
	private ServerSocket svrSocket;
	private Socket socket;
	private InputStream inputStream;
	private OutputStream outputStream;
	private ObjectInputStream objectInputStream;
	private ObjectOutputStream objectOutputStream;
	
	private ObjectInputStream objectInputStreamFile;
	private ObjectOutputStream objectOutputStreamFile;
	
	private FileInputStream fileInput;
	private FileOutputStream fileOutput;
	
	public SchoolServer(){
		try {
			svrSocket = new ServerSocket(5555);
			socket = svrSocket.accept();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run(){
		try {
			fileInput = new FileInputStream("data.txt");
		} catch (FileNotFoundException e1) {
			System.out.println(e1.getMessage());
			try {
				File file = new File("data.txt");
				file.createNewFile();
				fileInput = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			inputStream = socket.getInputStream();
			objectInputStream = new ObjectInputStream(inputStream);
			Map<String, Vector<Person>> p = (Map<String, Vector<Person>>) objectInputStream.readObject();
			
			//읽기
			if(p.containsKey("read")){
				System.out.println("읽기됨");
				fileInput = new FileInputStream("data.txt");
				objectInputStreamFile = new ObjectInputStream(fileInput);
				Vector<Person> readObject = (Vector<Person>) objectInputStreamFile.readObject();
				
				outputStream = socket.getOutputStream();
				objectOutputStream = new ObjectOutputStream(outputStream);
				objectOutputStream.writeObject(readObject);
			}else if(p.containsKey("save")){
				//저장
				System.out.println("저장됨");
				fileOutput = new FileOutputStream("data.txt");
				objectOutputStreamFile = new ObjectOutputStream(fileOutput);
				objectOutputStreamFile.writeObject(p.get("save"));
			}
			
			
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				objectInputStream.close();
				objectInputStreamFile.close();
				inputStream.close();
				outputStream.close();
				objectOutputStream.close();
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
	}
	
	public static void main(String aer[]){
		SchoolServer sc = new SchoolServer();
		sc.run();
	}

}
